import React, { useCallback, useState, useEffect, useRef } from 'react';
import { Table, Radio, message, Popconfirm, Button, Upload } from 'antd';
import { useSearchParams } from 'react-router-dom'
import request, { host } from '@/utils/request';
import moment from 'moment';
import { DeleteOutlined, UploadOutlined, VerticalAlignBottomOutlined } from '@ant-design/icons';
import ChangeItem from './ChangeItem';
import AddItem from './AddItem';
import ClassDetail from './ClassDetail';
import store from '@/store'

function ClassList() {
  const [datalist, setDatalist] = useState([])
  const [total, setTotal] = useState(0)
  const [selectionType, setSelectionType] = useState('checkbox');
  const [search, setSearch] = useSearchParams();
  const [params, setParams] = useState({
    page: search.get('page') * 1 || 1,
    size: search.get('size') * 1 || 10
  })
  const [rowKeys, setRowKeys] = useState([])
  const columns = [
    {
      title: '#',
      render(text, record, index) {
        // console.log('render',text, record, index)
        // text: dataIndex对应的数据，如不设置dataIndex则与record相同
        // record：每一条数据
        // index: 当前数据对应的索引值
        return index + 1
      }
    },
    {
      title: '班级',
      dataIndex: 'name',
    },
    {
      title: '课程',
      dataIndex: 'category',
    },
    {
      title: '城市',
      dataIndex: 'city',
    },
    {
      title: '开学时间',
      dataIndex: 'add_time',
      render(text) {
        return moment(text).format('YYYY-MM-DD')
      }
    },
    {
      title: '操作',
      dataIndex: '_id',
      render: (id, record, index) => (
        <>
          <ClassDetail lookItem={lookItem.bind(null, id)} classDetail={record} />
          <ChangeItem changeItem={changeItem.bind(null, id)} currentData={record} />
          <Popconfirm
            title="确定是否删除？"
            onConfirm={confirm.bind(null, id)}
            onCancel={cancel}
            okText="是"
            cancelText="否"
            icon={<DeleteOutlined />}
          >
            <a href="#"><DeleteOutlined />删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  // 班级列表
  const getData = useCallback(async () => {
    const { data } = await request.get('/class', {
      params
    })
    console.log('请求数据', data)
    setDatalist(data.data.result)
    setTotal(data.data.total)
  }, [params])

  useEffect(() => {
    getData()
  }, [params])

  // 查看单个班级
  const lookItem = useCallback(async (id) => {
    const { data } = await request.get('/class/' + id, { params })
    if (data.code === 200) {
      console.log('单个', data)
    }
  }, [params])

  // 增加
  const addRow = useCallback(async (stu) => {
    const { data } = await request.post('/class', stu)
    if (data.code === 201) {
      getData()
      message.success('添加成功');
    }
  }, [getData])

  // 删除
  const confirm = useCallback(async (id) => {
    const { data } = await request.delete('/class/' + id)
    if (data.code === 204) {
      getData()
      message.success('删除成功');
    }
  }, [getData])

  const cancel = () => {
    message.error('失败');
  };

  // 修改
  const changeItem = useCallback(async (id, stu) => {
    const { data } = await request.put('/class/' + id, stu)
    if (data.code === 201) {
      getData()
      message.success('修改成功');
    }
  }, [getData])

  // 批量删除
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setRowKeys(selectedRowKeys)
    },
  };
  const removeItem = useCallback(async (rowKeys) => {
    if (rowKeys.length === 0) {
      message.error('请勾选删除的数据')
      return
    }
    const { data } = await request.delete('/class', {
      data: {
        ids: rowKeys
      }
    })
    if (data.code === 204) {
      getData()
      message.success('删除成功');
    }
  }, [getData])

  // 上传
  const { userInfo: { authorization } } = store.getState()
  const props = {
    name: 'list',
    method:'post',
    action: host + '/api/class/import',
    headers: {
      authorization: authorization,
    },
  
  onChange(info){
    console.log(info)
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 文件上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 文件上传失败`);
    }
  }
}


  //导出
  const download = () => {
    const { userInfo: { _id } } = store.getState();
    request.post('/class/export', {
      userid: _id,
      ids: rowKeys,
      type: 'xls'
      // type:'json'  指定json格式
    }, {
      responseType: 'arraybuffer',
    }).then(res => {
      var blob = new Blob([res.data], {//这个里面的data 的二进制文件 创建一个文件对象
        type: 'application/vnd.ms-excel;charset=utf-8'
      })
      var downloadElement = document.createElement('a')//创建一个a 虚拟标签
      var href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download =
        decodeURI(
          res.headers['content-disposition'].split('filename=')[1]
        ) || '' // 下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象
      message.success('导出成功')
    }).catch((res) => {
      console.log('res', res)
    })
  }

  const pagination = {
    total,
    size: 'small',
    defaultCurrent: params.page,
    defaultPageSize: params.size,
    pageSize: params.size,
    current: params.page,
    pageSizeOptions: [10],
    onChange(page, size) {
      setParams({
        page,
        size
      })
      // 修改url地址参数
      setSearch({
        page,
        size
      })
    }
  }
  return (
    <div>
      <AddItem addRow={addRow} />
      <Button type="primary" size="small" icon={<DeleteOutlined />} style={{ marginRight: 5 }}
        onClick={() => {
          removeItem(rowKeys)
        }}>批量删除</Button>
      <Button icon={<UploadOutlined />} type="primary" size="small" style={{ marginRight: 5 }}
        onClick={download}>
        导出</Button>
      <Upload {...props} >
        <Button icon={<VerticalAlignBottomOutlined />} type="primary" size="small" >
          上传
        </Button>
      </Upload>
      <Radio.Group
        onChange={({ target: { value } }) => {
          setSelectionType(value);
        }}
        value={selectionType}
      >
      </Radio.Group>
      <Table
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
        columns={columns}
        dataSource={datalist}
        rowKey='_id'
        pagination={pagination}

      />
    </div>
  );
};


export default ClassList